/*  NVS: non volatile storage in flash
 *
 * Copyright (c) 2023 Liuis
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2023-09-03     Liuis        The first version.
 */

#include "nvs.h"
#include <stdio.h>
#include <string.h>

#define NVS_PAGE_SIZE   1024
uint8_t flash[NVS_PAGE_SIZE * 3];

int flash_init (void)
{
    memset(flash, 0xff, sizeof(flash));
    
    return 0;
}

int flash_read (uint32_t addr, void * data, size_t len)
{
    memcpy(data, (uint8_t *)(flash + addr), len);

    return 0;
}

int flash_write (uint32_t addr, const void * data, size_t len)
{
    memcpy((uint8_t *)(flash + addr), data, len);

    return 0;
}

int flash_erase (uint32_t addr, size_t len)
{
    memset((uint8_t *)(flash + addr), 0xff, NVS_PAGE_SIZE);
    
    return 0;
}

const static struct flash_parameters flash_param =
{
    4, 0xff, 1024,
    flash_init, 
    flash_read, 
    flash_write, 
    flash_erase
};



/////////////////////////////////////////////////////////////////////////////////


struct nvs_fs fs = 
{
    .offset = 0,
    .sector_size = 512,
    .sector_count = 3,
    .flash_params = &flash_param,
};

#define KEY_5   0x0505
uint8_t a5[5] = {0x55, 0x55, 0x55, 0x55, 0x55};

int main(int argc, char **argv) 
{
    uint32_t i; 
    int len;
    char str[20];
    uint32_t cnt=0;
    uint8_t buf[40];
    
    if (nvs_mount(&fs))
    {
        printf("init error!\n");
        return -1;
    }
    
    nvs_write(&fs, KEY_5, a5, sizeof(a5));
    len = nvs_read(&fs, KEY_5, buf, sizeof(a5));
    if (len <= 0)
    {
        printf("key not found!\n");
    }
    else
    {
        printf("key read ok!\n");
    }
    
    nvs_delete(&fs, KEY_5);
}
